package org.lw.ssm.controller;


import org.lw.ssm.Entity.Department;
import org.lw.ssm.Entity.Employee;
import org.lw.ssm.response.ApiResponse;
import org.lw.ssm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/departments")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;  // 注入服务层

    // 获取所有部门
    @GetMapping
    public ResponseEntity<ApiResponse<List<Department>>> getAllDepartments() {
        return
                ResponseEntity.ok().body(new ApiResponse<>(200, "所有部门信息", departmentService.getAllDepartments()));
    }

    // 根据ID获取某个部门信息
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Department>> getDepartmentById(@PathVariable("id") Long id) {
        Optional<Department> departmentOptional = departmentService.getOptionalDepartmentById(id);
        return departmentOptional.map(department -> ResponseEntity.ok().body(new ApiResponse<>(200, "部门信息", department)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ApiResponse<>(404, "部门不存在", null)));
    }

    // 创建新的部门
    @PostMapping
    public void createDepartment(@RequestBody Department department) {
        departmentService.createDepartment(department);
    }

    // 更新部门信息
    @PutMapping("/{id}")
    public void updateDepartment(@PathVariable("id") Long id, @RequestBody Department department) {
        department.setId(id); // 设置要更新的部门ID
        departmentService.updateDepartment(department);
    }

    // 删除部门
    @DeleteMapping("/{id}")
    public void deleteDepartment(@PathVariable("id") Long id) {

        departmentService.deleteDepartment(id);
    }
}
